package com.cspg.ssss.service;

import com.alibaba.fastjson.JSONObject;
import com.cspg.ssss.config.WeixinProperties;
import com.cspg.ssss.util.HttpRequest;
import com.cspg.ssss.vo.UserDetailInfoVo;
import com.cspg.ssss.vo.UserListVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WxUserService {
    private static final Logger log = LoggerFactory.getLogger(WxUserService.class);

    @Autowired
    WeixinService wxService;

    @Autowired
    WeixinProperties wxProperties;

    public UserListVo getUserListByDepartmentId (String corpid, String corpsecret, String departmentId, String fechFlag) {
        String token = wxService.getToken(corpid,corpsecret);
        String getUrl = wxProperties.getUrlroot()+"/cgi-bin/user/simplelist?access_token=" + token + "&department_id=" + departmentId + "&fetch_child=" + fechFlag;
        JSONObject retobj = HttpRequest.httpsGetRequest(getUrl);
        log.debug("getUserListByDepartmentId："+retobj.toJSONString());
        UserListVo vo = JSONObject.toJavaObject(retobj, UserListVo.class);
        return vo;
    }

    public UserDetailInfoVo getWxUserInfoByUserId(String token, String userId) {
//        String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=" + token + "&department_id=" + departmentId + "&fetch_child=" + fechFlag;
        String getUrl = String.format("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s", token, userId);
        JSONObject retobj = HttpRequest.httpsGetRequest(getUrl);
        if( !retobj.getString("errcode").equals("0"))
        {
            log.error("获取企业用户详细信息失败："+ retobj.toJSONString());
            return null;
        }
        log.debug("getWxUserInfoByUserId："+retobj.toJSONString());
        UserDetailInfoVo vo = new UserDetailInfoVo();
        vo.setUserid(retobj.getString("userid"));
        vo.setName(retobj.getString("name"));
        vo.setMobile(retobj.getString("mobile"));
        vo.setEmail(retobj.getString("email"));
        vo.setEnable(retobj.getString("enable"));
        vo.setStatus(retobj.getString("status"));
        return vo;
    }

}
